package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.bean.OrderPage;
import com.itheima.bean.Orders;
import com.itheima.bean.R;
import com.itheima.service.OrdersService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Slf4j
@RequestMapping("/order")
@RestController
public class OrderController {

    @Autowired
    private OrdersService ordersService;

    @GetMapping("/page")
    public R page(OrderPage orderPage){
        Page<Orders> pageOrder = new Page<>(orderPage.getPage(), orderPage.getPageSize());
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(orderPage.getNumber()!=null,Orders::getNumber,orderPage.getNumber());


        if(orderPage.getBeginTime()!=null&&orderPage.getEndTime()!=null){
            String sBegin = orderPage.getBeginTime();
            String sEnd = orderPage.getEndTime();
            DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDateTime beginTime = LocalDateTime.parse(sBegin, df);
            LocalDateTime endTime=LocalDateTime.parse(sEnd,df);
            wrapper.between(Orders::getOrderTime,beginTime,endTime);
        }

        Page<Orders> page = ordersService.page(pageOrder, wrapper);
        return R.success(page);
    }


    @PostMapping("/submit")
    public R submit(@RequestBody Orders orders){
        log.info("orderss:{}",orders);

        boolean flag = ordersService.submit(orders);

        return flag?R.success("下单成功！"):R.error("下单失败！");
    }

    @PutMapping
    public R update(@RequestBody Orders orders) {
        boolean flag = ordersService.updateById(orders);
        return flag?R.success("状态更新完成！"):R.error("状态更新失败！");
    }

}
